package com.cht.commonUtil.infra;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cht.commonUtil.jqGrid.ResultTableSet;
import com.cht.commonUtil.jqGrid.Rows;
import com.cht.commonUtil.structure.InfoStruc;
import com.cht.commonUtil.webInit.SP;
import com.cht.commonUtil.widgets.Widgets;
import com.google.gson.Gson;

public class QuerySqGroup extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding( SP.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( SP.UIcodeSet );
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		ResultSet rs2 = null;
		
		String sql = "";
		ResultTableSet resultTableSet = new ResultTableSet();
		
		/*	決定執行動作型態
		 * 		1.	產生 grid
		 * 		2. 產生 id & name
		 * 		3. 產生 id & name 及下轄的資源群組
		 * 
		 * 	*/
		int actType = Integer.parseInt( request.getParameter("fc") );
		sql = "SELECT COUNT(*) FROM squadgroup WHERE subsysid=?";
		
		ArrayList<InfoStruc> infoStrucs = new ArrayList<InfoStruc>();
		
		String sord = request.getParameter("sord");
		String sidx =  request.getParameter("sidx");
		
		int total_pages = 1;
		int count  = 0; 
		int page = 1;
		int limit = 10;
		
		if ("".equalsIgnoreCase(sidx)|| sidx==null) {
			sidx = "sqgruseqname";
		} 
		if ("".equalsIgnoreCase(sord)|| sord==null) {
			sord = "ASC";
		} else {
			page = Integer.parseInt(request.getParameter("page"));
			limit = Integer.parseInt(request.getParameter("rows"));
		}
		
		String subsysId = request.getParameter("subsysId");
		
		try {
			conn = Widgets.getConn();	
			ps = conn.prepareStatement(sql);
			ps.setString(1, subsysId);	
			
			rs = ps.executeQuery();
			rs.next();
			count  = rs.getInt(1);
			
			if ( count  != 0 ) {
				
				if (limit  < count) {
					total_pages = (count / limit)+1;	
				}

				if ( conn.getMetaData().getDatabaseProductName().contains( "MySQL" ) ) {
					sql = "SELECT t1.sqgruseqid,t1.sqgruseqname,t1.creator, t1.createdDateTime FROM squadgroup t1 WHERE t1.subsysid=?  ORDER BY "+sidx+" "+sord+" LIMIT "+(limit*page-limit)+","+ limit;
				} else if ( conn.getMetaData().getDatabaseProductName().contains( "Informix" ) ) {
					sql = "SELECT SKIP "+(limit*page-limit)+" FIRST "+ limit +" t1.sqgruseqid,t1.sqgruseqname,t1.creator, t1.createdDateTime FROM squadgroup t1 WHERE t1.subsysid=?  ORDER BY "+sidx+" "+sord;
				}
				if ( rs != null ) { rs.close(); }
				if ( ps!= null ) { ps.close(); }
				ps = conn.prepareStatement(sql);
				ps.setString(1,subsysId);
				rs = ps.executeQuery();
				ArrayList<Rows> rows = new ArrayList<Rows>();
				
				while ( rs.next() ) {
					String sqgruseqid = rs.getString("sqgruseqid");
					
					if ( actType == 1 ) {
						Rows row = new Rows();
						row.setId(sqgruseqid);
						String[] cell = new String[2];
						cell[0] = sqgruseqid;
						cell[1] = rs.getString("sqgruseqname");
						row.setCell(cell);
						rows.add(row);						
					}  else if ( actType == 2 || actType == 3 ) {
						InfoStruc infoStruc = new InfoStruc();
						infoStruc.setId( sqgruseqid );
						infoStruc.setName( rs.getString("sqgruseqname") );
						
						sql = "SELECT t2.squadid AS i,t1.subsysid,t1.squadid,t1.squadname FROM squad t1, OUTER mpsquadgroupsquads t2 WHERE t1.subsysid = t2.subsysid AND t1.subsysid=? AND t1.squadid=t2.squadid AND t2.sqgruseqid=?";
						if ( actType == 3 ) {
							ps = conn.prepareStatement(sql);
							ps.setString(1, subsysId);	
							ps.setInt(3, Integer.parseInt( sqgruseqid ));
							rs2 = ps.executeQuery();
							String tmp="";
							while( rs2.next() ) {
								if ( rs2.getString("i") != null ) {
									tmp += rs2.getString("squadid")+Widgets.splitTokenONE;
								}
							}
							if ( tmp.length() !=0 ) {
								tmp = tmp.substring(0, tmp.length()-Widgets.splitTokenONE.length() );
								infoStruc.setSquadPath(tmp);
							}
						}
						
						infoStrucs.add(infoStruc);
					}
						
				}
				
				resultTableSet.setRows( rows );
				resultTableSet.setPage( String.valueOf(page) );
				resultTableSet.setTotal( total_pages );
				resultTableSet.setRecords( String.valueOf(count) );
				
			} else {
				page =0;
				total_pages=0;
				resultTableSet.setPage( String.valueOf(page) );
				resultTableSet.setTotal( total_pages );
				resultTableSet.setRecords( String.valueOf(count) );
			}
		} catch ( Exception e) {
			Widgets.errLog(e);
		} finally {
			try {
				if ( rs != null ) { rs.close(); }
				if ( rs2 != null ) { rs2.close(); }
				if ( ps!= null ) { ps.close(); }
				if ( conn!= null ) { conn.close(); }
			} catch (SQLException e) {e.printStackTrace(); }
		}
		if ( actType == 1 ) {
			response.getWriter().write(new Gson().toJson(resultTableSet));
		} else if ( actType == 2 || actType ==3 ) {
			response.getWriter().write(new Gson().toJson(infoStrucs));
		}
	}

}
